//
//  MarkerPlaceViewController.m
//  XinKaiFa55like
//
//  Created by 55like on 2017/9/26.
//  Copyright © 2017年 55like lj. All rights reserved.
//

#import "MarkerPlaceViewController.h"
#import "MarkerPiaceCell.h"
#import "MarkerImageTableViewCell.h"
#import "NSObject+JSONCategories.h"


@interface MarkerPlaceViewController ()

@property(nonatomic,strong)UITableView * zhltableView;

@property (nonatomic,strong)UIButton * fooderButton;

@property (nonatomic,strong)NSMutableDictionary * postData;
@property (nonatomic,strong)NSMutableArray * imageArray;
@property (nonatomic,strong)NSMutableArray * remArray;
@property (nonatomic,strong)NSMutableArray * pathArray;
//是否可以编辑1全部 2部分
@property (nonatomic,strong)NSString * isedit;
//是否显示备注
@property (nonatomic,assign)BOOL remarkHide;
@property (nonatomic,assign)CGFloat cellHeight;
@end

@implementation MarkerPlaceViewController
{
    CGFloat jipanhigt;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.remarkHide = NO;
    self.postData = [[NSMutableDictionary alloc]init];
    self.imageArray = [[NSMutableArray alloc]init];
    self.remArray = [[NSMutableArray alloc]init];
    self.pathArray = [[NSMutableArray alloc]init];
    [self fooderButton];
    
    if ([self.userInfo valueForJSONStrKey:@"id"].length > 0) {
        
        self.remarkHide = YES;
        [self makeData];
        
    }else{
        
        UIImage * image = [UIImage imageNamed:@"zdyadd"];
        [self.imageArray addObject:image];
        self.cellHeight = ((self.imageArray.count % 4 == 0?0:1) + self.imageArray.count / 4) * (kScreenWidth - 20)/4;
        [self.zhltableView reloadData];
    }
    
    
    EMWeakSelf(weakSelf);
    [self.navView addViewClickBlock:^(UIView *view) {
       
        [weakSelf.view endEditing:YES];
        
    }];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWasShow:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
}
//获取数据
-(void)makeData{
    
    
    krequestParam
    [dictparam setValue:[self.userInfo valueForJSONStrKey:@"id"] forKey:@"id"];
    [NetEngine createHttpAction:@"customer/slip_detail" withCache:NO withParams:dictparam withMask:SVProgressHUDMaskTypeClear onCompletion:^(id resData, BOOL isCache) {
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
            
            NSDictionary * dic = resData[@"data"][@"detail"];
            
            self.postData = [[NSMutableDictionary alloc]initWithDictionary:dic];
            NSArray * pathArray = [self.postData[@"path"] mutableCopy];
            self.pathArray = [[NSMutableArray alloc]initWithArray:pathArray];
            UIImage * image = [UIImage imageNamed:@"zdyadd"];
            
            for (int i = 0; i < self.pathArray.count; i ++) {
                
                NSString * path = [self.pathArray[i] valueForJSONStrKey:@"url"];
                [self.imageArray addObject:path];
        
            }
            [self.imageArray addObject:image];
            self.cellHeight = ((self.imageArray.count % 4 == 0?0:1) + self.imageArray.count / 4) * (kScreenWidth - 20)/4;
            self.isedit = [self.postData valueForJSONStrKey:@"isedit"];
            [self.zhltableView reloadData];
            
        }else{
            
            
            
            
            
            
        }
        
    } onError:^(NSError *error) {
        
    }];
    
    
    
    
    
}
-(void)ifsave{
    
    EMWeakSelf(weakSelf);
    [QAlertController showAlertQAlertControllerWithTitle:@"是否提交？" message:@"" cancelBtn:@"取消" otherBtnArray:@[@"确定"] showController:self QAlertControllerClickBlock:^(int index) {
       
        if (index == 1) {
            
            
            [weakSelf save];
            
        }
        
        
    }];
    
    
}
//提交
-(void)save{
    
    
    NSMutableArray * imageArr = [[NSMutableArray alloc]init];
    
    for (int i = 0; i < self.imageArray.count - 1; i ++) {
        
        id image = self.imageArray[i];
        if ([image isKindOfClass:[UIImage class]]) {
        
            [imageArr addObject:image];
        
        }
   
    }
    
    NSMutableArray *fileData = [[NSMutableArray alloc] init];
    for (int i = 0; i < imageArr.count; i++) {
        
        UIImage *image = imageArr[i];
        
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation([[Utility Share]imageWithImageSimple:image scaledToSize:CGSizeMake(image.size.width, image.size.height)], 1),@"fileData",@"path[]",@"fileKey",@"aa.jpg",@"fileName",@"image",@"fileType", nil];
        
        [fileData addObject:dic];
    }
    [self.postData setValue:[UTILITY userId] forKey:@"uid"];
    [self.postData setValue:[UTILITY userToken] forKey:@"token"];
    [self.postData setValue:[self.userInfo valueForJSONStrKey:@"id"] forKey:@"id"];
    [self.postData setValue:[self.remArray componentsJoinedByString:@","] forKey:@"pathid"];
    
    [NetEngine uploadAllFileAction:@"customer/updateslip" withParams:self.postData fileArray:fileData onCompletion:^(id resData, BOOL isCache) {
        
        [QAlertView showAlertViewWithTitle:[resData valueForJSONStrKey:@"info"] message:nil cancelButtonTitle:@"确定" OtherButtonsArray:nil clickAtIndex:^(NSInteger index) {
            
        }];
        
        if ([[resData valueForJSONStrKey:@"status"] isEqualToString:@"200"]) {
          
            [self backButtonClicked:nil];
            
        }else{
            
            
            
        }
        
        [SVProgressHUD dismiss];
        
    } onError:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:@"请检查网络连接~"];

    } withMask:SVProgressHUDMaskTypeClear];

    
}

static NSString * MarkerPiaceCellID  = @"MarkerPiaceCellID";
static NSString * MarkerImageTableViewCellID  = @"MarkerImageTableViewCellID";

-(UITableView *)zhltableView{
    
    if (!_zhltableView) {
        
        UITableView * zhltableView =[[UITableView alloc]initWithFrame:CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 - 50) style:UITableViewStyleGrouped];
        zhltableView.delegate = self;
        zhltableView.dataSource = self;
        zhltableView.backgroundColor = [UIColor whiteColor];
        zhltableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        zhltableView.showsVerticalScrollIndicator = NO;
        zhltableView.showsHorizontalScrollIndicator = NO;
        zhltableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
        zhltableView.sectionHeaderHeight = 0;
        zhltableView.sectionFooterHeight = 0;
        [self.view addSubview:zhltableView];
        [zhltableView registerClass:[MarkerPiaceCell class] forCellReuseIdentifier:MarkerPiaceCellID];
        [zhltableView registerClass:[MarkerImageTableViewCell class] forCellReuseIdentifier:MarkerImageTableViewCellID];
        _zhltableView = zhltableView;
    }
    
    return _zhltableView;
}
#pragma mark -  tableview代理方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    
    return self.titleArray.count;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    NSString * title = self.titleArray[section];
    if ([title isEqualToString:@"备注"]) {
        
        if (self.remarkHide) {
            
            
            return 2;
            
        }
    }
    
    return 1;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * title = self.titleArray[indexPath.section];
    if ([title isEqualToString:@"备注"]) {
        
        if (indexPath.row == 1) {
            
            
               return 90 + self.cellHeight;
            
        }
    }
    
    return 44;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    
    return CGFLOAT_MIN;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section    {
    
    
    
    return CGFLOAT_MIN;
}


#pragma mark  cell处理
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    EMWeakSelf(weakSelf);
    NSString * title = self.titleArray[indexPath.section];
    if ([title isEqualToString:@"备注"]) {
        
        if (indexPath.row == 1) {
            
            
            MarkerImageTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:MarkerImageTableViewCellID forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.line.frameY = cell.frameHeight - 1;
            cell.textview.text = [self.postData valueForJSONStrKey:@"descr"];
            cell.imageEditorV.imageArray = self.imageArray;
            [cell.imageEditorV reshData];
            cell.textblock = ^(NSString *text) {
              
                [weakSelf.postData setValue:text forKey:@"descr"];
                
            };
            cell.imageEditorV.imageBlock = ^(NSMutableArray *imageArr, CGFloat cH) {
              
                
                weakSelf.imageArray = imageArr;
                weakSelf.cellHeight = cH;
                [weakSelf.zhltableView reloadData];
                
            };
            cell.imageEditorV.remBlock = ^(NSInteger row) {
              
                if (weakSelf.pathArray.count > row) {
                    
                    NSString * idd = [[weakSelf.pathArray[row] valueForJSONStrKey:@"id"] mutableCopy];
                    [weakSelf.remArray addObject:idd];
                    [weakSelf.pathArray removeObjectAtIndex:row];
                }
                
                
                
            };
            
            return cell;
        }
    }
    
    
    
    
    MarkerPiaceCell * cell = [tableView dequeueReusableCellWithIdentifier:MarkerPiaceCellID forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.indexPath = indexPath;
    cell.line.hidden = NO;
    cell.titleLab.frame = CGRectMake(10, 0, [title widthWithFont:15], cell.frameHeight);
    cell.titleLab.text = title;
    cell.textField.frame = CGRectMake(XW(cell.titleLab) + 10, 0, kScreenWidth - 10 - XW(cell.titleLab) - 10, cell.frameHeight);
    cell.textField.text = self.desArray[indexPath.section];
    cell.icon.frame = CGRectMake(kScreenWidth - 10 - 8, (cell.frameHeight - 29/2)/2, 8, 29/2);
    cell.icon.image = [UIImage imageNamed:@"xkf_searrighticon"];
    
    if ([self.isedit isEqualToString:@"2"]) {
        
        
        cell.textField.userInteractionEnabled = NO;
    }else{
        
        cell.textField.userInteractionEnabled = YES;

    }
    
    cell.icon.hidden = YES;
    cell.textField.placeholder = @"请输入";
    
    if ([title isEqualToString:@"性质"] ||
        [title isEqualToString:@"日期"] ||
        [title isEqualToString:@"备注"]) {
        cell.textField.placeholder = @"";
        cell.textField.frameWidth = X(cell.icon) - XW(cell.titleLab) - 20;
        cell.textField.userInteractionEnabled = NO;
        cell.icon.hidden = NO;
        
        if ([title isEqualToString:@"备注"] && self.remarkHide == YES) {
            
            cell.icon.frame = CGRectMake(kScreenWidth - 10 - 15, (cell.frameHeight - 17/2)/2, 15, 17/2);
            cell.icon.image = [UIImage imageNamed:@"xkf_xiala2"];
            
        }
        
        
    }
   
    cell.textBlock = ^(NSString *text, NSIndexPath *indexp) {
        
        NSString * textStr = weakSelf.titleArray[indexp.section];
        
        if ([textStr isEqualToString:@"公司名称"]) {
            
            [weakSelf.postData setValue:text forKey:@"companyname"];
            
        }else if ([textStr isEqualToString:@"姓名"]) {
            
            [weakSelf.postData setValue:text forKey:@"name"];
            
        }else if ([textStr isEqualToString:@"手机"]) {
            
            [weakSelf.postData setValue:text forKey:@"mobile"];
            
        }else if ([textStr isEqualToString:@"微信"]) {
            
            [weakSelf.postData setValue:text forKey:@"wechat"];
            
        }else if ([textStr isEqualToString:@"合同编号"]) {
            
            [weakSelf.postData setValue:text forKey:@"contract"];
            
        }else if ([textStr isEqualToString:@"售价(万)"]) {
            
            [weakSelf.postData setValue:text forKey:@"price"];
            
        }else if ([textStr isEqualToString:@"结算价(万)"]) {
            
            [weakSelf.postData setValue:text forKey:@"saleprice"];
            
        }
        
        
        
    };
    
    
    
    return cell;
    
}
#pragma mark  选中cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self.view endEditing:YES];
    
    if ([self.isedit isEqualToString:@"2"]) {
        
        return;
    }
    EMWeakSelf(weakSelf);
    NSString * title = self.titleArray[indexPath.section];
    if ([title isEqualToString:@"性质"]) {
        
        [QAlertController showSheetQAlertControllerWithTitle:@"性质" message:@"" cancelBtn:@"取消" otherBtnArray:@[@"中介",@"直客"] showController:self QAlertControllerClickBlock:^(int index) {
           
            
            if (index == 1) {
                
                [weakSelf.postData setValue:@"1" forKey:@"nature"];
             
                
            }else if(index == 2){
                
                [weakSelf.postData setValue:@"2" forKey:@"nature"];
             
                

            }
            
            [weakSelf.zhltableView reloadData];
            
        }];
        
        
        
    }else if ([title isEqualToString:@"日期"]) {
        
        
        [QDatePickerView showModeDateQDatePickerViewWithTitle:@"选择日期" datePickerOkBtnAction:^(NSString *dateStr) {
           
            
            [weakSelf.postData setValue:dateStr forKey:@"suctime"];
            [weakSelf.zhltableView reloadData];
            
        }];
        
        
        
        
        
    }else if ([title isEqualToString:@"备注"]){
        
        if (indexPath.row == 0) {
            
            self.remarkHide = !self.remarkHide;
            
            [self.zhltableView reloadData];
            
        }
        
       
        
        
        
    }
    
    
    
}
-(NSArray *)desArray{
    
    NSString * xinzhi = @"";
    if ([[self.postData valueForJSONStrKey:@"nature"] isEqualToString:@"2"]) {
        xinzhi = @"直客";
    }else{
        xinzhi = @"中介";
        [self.postData setValue:@"1" forKey:@"nature"];
    }
    
    return @[[self.postData valueForJSONStrKey:@"companyname"],
             [self.postData valueForJSONStrKey:@"name"],
             [self.postData valueForJSONStrKey:@"mobile"],
             [self.postData valueForJSONStrKey:@"wechat"],
             xinzhi,
             [self.postData valueForJSONStrKey:@"suctime"],
             [self.postData valueForJSONStrKey:@"contract"],
             @"",
             [self.postData valueForJSONStrKey:@"price"],
             [self.postData valueForJSONStrKey:@"saleprice"],
             ] ;
}
-(NSArray *)titleArray{
    
    return @[@"公司名称",@"姓名",@"手机",@"微信",@"性质",@"日期",@"合同编号",@"备注",@"售价(万)",@"结算价(万)"];
    
}
-(UIButton *)fooderButton{
    
    if (!_fooderButton) {
        
        UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50)];
        [button setTitle:@"发布" forState:UIControlStateNormal];
        button.titleLabel.font = Font(16);
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = rgb(239,186,58);
        [button addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
        _fooderButton = button;
        
    }
    
    
    return _fooderButton;
}
- (void)keyboardWasShow:(NSNotification *)notification
{
    CGRect keyboardFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat transformY = keyboardFrame.origin.y - kScreenHeight;
    
    if (transformY < 0 && transformY < jipanhigt) {
        
        [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            //        self.view.frame = CGRectMake(0, 0, DEV_W,self.view.frame.size.height+transformY);
            jipanhigt = transformY;
            self.zhltableView.frame = CGRectMake(0, 64, kScreenWidth, kScreenHeight - 64 + transformY);
            
            //随之tableview的高度变化
            //        botView.frame = CGRectMake(0, CGRectGetMaxY(mTableView.frame), DEV_W, FOOT_H);
        }];
        self.zhltableView.contentOffset = CGPointMake(0, self.zhltableView.contentOffset.y - transformY);
        
        
    }else if(transformY >= 0){
        
        
        
        [UIView animateWithDuration:[notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue] animations:^{
            //        self.view.frame = CGRectMake(0, 0, DEV_W,self.view.frame.size.height+transformY);
            jipanhigt = transformY;
            
            self.zhltableView.frame = CGRectMake(0,64, kScreenWidth, kScreenHeight - 64 - 50);
            
            //随之tableview的高度变化
            //        botView.frame = CGRectMake(0, CGRectGetMaxY(mTableView.frame), DEV_W, FOOT_H);
        }];
        
        
        
    }
    
    
    
}
-(void)backButtonClicked:(id)sender{
    
    
    [[NSNotificationCenter defaultCenter]postNotificationName:@"CRMList" object:nil];
    
    
    [super backButtonClicked:sender];
}
@end
